package com.jhd.fuzhou.service;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.pdf.PdfRenderer;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.widget.Button;
import android.widget.Toast;

import com.epson.isv.eprinterdriver.Common.EpsPrinter;
import com.epson.isv.eprinterdriver.Common.EpsStatus;
import com.epson.isv.eprinterdriver.Common.ServiceIntent;
import com.epson.isv.eprinterdriver.Ctrl.EPSetting;
import com.epson.isv.eprinterdriver.Ctrl.EPrintManager;
import com.epson.isv.eprinterdriver.Ctrl.IPrintListener;
import com.epson.isv.eprinterdriver.Ctrl.ISearchPrinterListener;
import com.epson.isv.eprinterdriver.Ctrl.PageAttribute;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/*爱普生打印机*/
public class EPrinterService implements ISearchPrinterListener, IPrintListener {

    private EPSetting setting;
    private Context mContext;
    private ProgressDialog progressDialog;
    private List<EpsPrinter> mPrinterList = new ArrayList<>();
    EPrintManager epManager;
    private List<Bitmap> bitmapList = new ArrayList<>();
    private List<String> pathList = new ArrayList<>();
    public final static int MSG_UPDATE_TEXT	= 0;
    public Button mButton;

    public EPrinterService(Builder builder) {
        this.mContext = builder.mContext;
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setCanceledOnTouchOutside(false);
        epManager = EPrintManager.instance();
        setting = EPSetting.instance();
        epManager.addSearchListener(this);
        epManager.findPrinter(20);//再搜
    }
    public static final class Builder {
        private Context mContext;
        public Builder(Context val) {
            mContext = val;
        }
        public EPrinterService build() {
            return new EPrinterService(this);
        }
    }

    public void executePrint(Button button) {
        mButton=button;
        if(mPrinterList.size()==0){//判断是否搜索到打印机
            showToast("未搜索到打印机！");
            epManager.findPrinter(20);//再搜
            return;
        }else{
            pdf2Img();
        }
    }

    @Override
    public void onSearchBegin() {
        //showToast("搜索");
    }

    /*搜索同一局域网的打印机*/
    @Override
    public void onFindPrinter(EpsPrinter printer) {
        mPrinterList.clear();
        mPrinterList.add(printer);
        if(mPrinterList.size()>0){
            epManager.cancelFindPrinter();
            setSelectedPrinter(mPrinterList.get(0));
        }
    }

    @Override
    public void onSearchFinished(int i) {
        //showToast("搜索结束");
    }


    private void setSelectedPrinter(EpsPrinter device) {
        setting.setSelEpsPrinter(mPrinterList.get(0));
        PageAttribute epPageAttri = new PageAttribute(PageAttribute.MediaSizeID.EPS_MSID_A4, PageAttribute.MediaTypeID.EPS_MTID_PLAIN, PageAttribute.PrintQuality.EPS_MQID_NORMAL);
        setting.setSelPageAttri(epPageAttri);
        setting.setPrintDirection(EPSetting.PRINT_DIR_BI);//BI做，EPSetting.PRINT_DIR_UNI不做
        setting.setColorMode(EPSetting.COLOR_MODE_COLOR);//
        setting.setPaperSource(EPSetting.PAPER_SOURCE_AUTO);
        setting.setBorderless(false);
        setting.setDuplexPrint(false);
        setting.setTemporaryImageFilePath(mContext.getExternalFilesDir(null).getPath() + "/Download/temp.jpg");
        epManager = EPrintManager.instance();
        epManager.addPrintListener(this);
    }

    @Override
    public void onPrintBegin() {
        Message msg = Message.obtain();
        msg.what = MSG_UPDATE_TEXT;
        msg.obj = (Object)("打印中...");
        mHandler.sendMessage(msg);
        statusDialog = null;
        System.gc();
    }

    @Override
    public String onPageBegin(int pageNum) {
        System.gc();
        return pathList.get(pageNum-1);
    }

    @Override
    public boolean onPageFinished(int finishedNum) {
        int totalPageNum = EPSetting.instance().getTotalPages();
        return finishedNum <= totalPageNum;
    }

    @Override
    public void onPrintFinished(int factor) {
        System.gc();
        String message;
        pathList.clear();
        switch (factor) {
            case ServiceIntent.StopFactor.PrintSuccess:
                message ="打印成功!";
                break;
            case ServiceIntent.StopFactor.PrinterStopButton:
                message = "打印停止!";
                break;
            case ServiceIntent.StopFactor.UserCancel:
                message ="用户取消!";
                break;
            case ServiceIntent.StopFactor.PrinterErrorOccur:
                message ="打印错误!";
                break;
            default:
                message = "其它错误!";
                break;
        }
        progressDialog.dismiss();
        showToast(message);
        mButton.setClickable(true);
    }

    @Override
    public void onPrintPause(int curNum, int pauseFactor, EpsStatus pauseStatus) {
        statusDialog = createStatusDialog(pauseStatus);
        statusDialog.show();
    }

    @Override
    public void onPrintResume() {
        dismissStatusDialog();
    }

    @Override
    public void onPrintAutoContinue() {;
        dismissStatusDialog();
    }

    @Override
    public void onCleaningTime(int seconds) {
        String s = "onCleaningTimeInformation = " + seconds + " seconds";
        showToast(s);
    }
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_TEXT:
                    String text = (String)msg.obj;
                    if(!progressDialog.isShowing()){
                        progressDialog.dismiss();
                        progressDialog.setMessage(text);
                        progressDialog.show();
                    }
                    break;
            }
        }
    };
    Dialog statusDialog = null;
    Dialog createStatusDialog(EpsStatus status) {
        if (statusDialog != null) {
            dismissStatusDialog();
        }

        String message = status.toString();
        final boolean continueable = status.isJobContinue();

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(message);
        builder.setCancelable(false);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                epManager.cancelPrint();
            }
        });

        if (continueable) {
            builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    epManager.continuePrint();
                }
            });
        }
        return builder.create();
    }
    void dismissStatusDialog() {
        if (statusDialog != null) {
            statusDialog.dismiss();
            statusDialog = null;
        }
    }


    private void showToast(final String message) {
        Toast.makeText(mContext,message,Toast.LENGTH_SHORT).show();
    }

    public void pdf2Img() {
        bitmapList.clear();
        try {
            ParcelFileDescriptor mFileDescriptor = ParcelFileDescriptor.open(new File(mContext.getExternalFilesDir(null).getPath() + "/Download/document.pdf"),ParcelFileDescriptor.MODE_READ_WRITE);
            //创建构建图片渲染句柄
            PdfRenderer mPdfRenderer = new PdfRenderer(mFileDescriptor);
            int count=mPdfRenderer.getPageCount();
            for (int i = 0; i < count; i++) {
                //选择渲染哪一页的渲染数据
                PdfRenderer.Page mCurrentPage = mPdfRenderer.openPage(i);
                Bitmap bitmap = Bitmap.createBitmap(
                        mContext.getResources().getDisplayMetrics().densityDpi * mCurrentPage.getWidth() / 72,
                        mContext.getResources().getDisplayMetrics().densityDpi * mCurrentPage.getHeight() / 72,
                        Bitmap.Config.ARGB_8888
                );
                Canvas canvas = new Canvas(bitmap);
                canvas.drawColor(Color.WHITE);
                canvas.drawBitmap(bitmap, 0, 0, null);
                mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
                saveBitmapFile(bitmap,i);
                bitmapList.add(bitmap);
                mCurrentPage.close();
            }
            epManager.startPrint();
            mButton.setClickable(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveBitmapFile(Bitmap bitmap,int i){
        File file=new File(mContext.getExternalFilesDir(null).getPath() + "/Download/"+i+".jpg");//将要保存图片的路径
        pathList.add(mContext.getExternalFilesDir(null).getPath() + "/Download/"+i+".jpg");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        setting.setTotalPages(pathList.size());
    }
}